/**
 * 该方法会把github的markdown处理成trac的markdown
 * @param {*} mdText 
 * @returns 
 */
function githubToTrac(mdText) {
    let codeBlocks = [];
    let placeholderCounter = 0;

    // 处理代码块
    function codeReplacer(match, language, code) {
        language = language || '';
        codeBlocks.push({ idx: placeholderCounter, lang: language, code: code });
        let placeholder = `__CODEBLOCK${placeholderCounter}__`;
        placeholderCounter++;
        return placeholder;
    }
    let codePattern = /```(\w*)\n([\s\S]*?)```/gm;
    let text = mdText.replace(codePattern, codeReplacer);

    // 处理标题
    text = text.replace(/^(#{1,6})\s+(.*?)$/gm, (match, level, title) => {
        let levelLen = level.length;
        title = title.trim();
        return `${'='.repeat(levelLen + 1)} ${title} ${'='.repeat(levelLen + 1)}`;
    });

    // 转换链接
    text = text.replace(/\[([^[\]]+)\]\(([^()]+)\)/g, '[$2 $1]');

    // 处理表格和---
    let lines = text.split('\n');
    let processed = [];
    let inTable = false;
    let skipNext = false;

    for (let i = 0; i < lines.length; i++) {
        let line = lines[i];
        if (skipNext) {
            skipNext = false;
            continue;
        }
        let strippedLine = line.trim();

        // 处理"---"行
        if (strippedLine === '---') {
            if (i + 1 < lines.length) {
                let nextLine = lines[i + 1].trim();
                if (/^={2,}\s.*?\s={2,}$/.test(nextLine)) {
                    skipNext = true;
                    continue;
                }
            }
            line = '------';
        }

        // 处理表格
        if (/^\|?.+\|.+\|?$/.test(line) && line.includes('|')) {
            if (!inTable) inTable = true;
            // 跳过分隔行
            if (/^\|?[\s|:-]+\|?$/.test(line)) continue;
            // 转换单元格
            let cells = line.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
            line = '||' + cells.join('||') + '||';
        } else {
            inTable = false;
        }
        processed.push(line);
    }
    text = processed.join('\n');

    // 转换斜体
    text = text.replace(/(?<!\*)\*(?!\*)([^*]+?)(?<!\*)\*(?!\*)/g, "''$1''");

    // 恢复代码块
    codeBlocks.forEach(cb => {
        let placeholder = `__CODEBLOCK${cb.idx}__`;
        let replacement;
        if (cb.lang) {
            replacement = `{{{#!${cb.lang}\n${cb.code}\n}}}`;
        } else {
            replacement = `{{{\n${cb.code}\n}}}`;
        }
        text = text.replace(placeholder, replacement);
    });

    return text;
}